//
//  HomeTableViewController.swift
//  WeiBo test
//
//  Created by Aquarius_wing on 16/5/4.
//  Copyright © 2016年 Wing. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class HomeTableViewController: BaseTableViewController,ReFreshViewDelegate {
    let cellReUseID="WeiboContent"
    let account=UserAccount?.self
    lazy var indicatorView:UIActivityIndicatorView={
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        return indicator
    }()
    var reFreshView:ReFreshView!
    
    //本页数据源
    var weiboContents:[WeiboContent]=[]
    
    let weiboContent=WeiboContentViewModel(count: 20)
    override func viewDidLoad() {
        super.viewDidLoad()
        if UserAccountViewModel().userLogin{
            print("已经登录了")
            setupUI()
            //当WeiboContentViewModel类中的weiboCOntent被设定值得时候
            NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.setupData), name: "weiboContentsDidSet", object: nil)
            tableView.registerClass(WeiboContentCell.self, forCellReuseIdentifier: cellReUseID)
            tableView.backgroundColor=UIColor(white: 244/255, alpha: 1)
        }else{
            print("没有登录")
            visitorLoginView?.setUIInfo(nil, title: "关注一些人,回这里看看有什么惊喜")
        }
    }
    
    func setupData(){
        weiboContents=weiboContent.weiboContents
        tableView.reloadData()
    }
    
    func setupUI(){
        //菊花View
        tableView.tableFooterView=indicatorView
        tableView.registerClass(WeiboContentCell.self, forCellReuseIdentifier:      cellReUseID)
//        tableView.rowHeight=100
        tableView.separatorStyle = .None
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
        self.navigationItem.rightBarButtonItem=UIBarButtonItem(title: "加载更多", style: .Plain, target: self, action: #selector(HomeTableViewController.addData))
        //下拉刷新
//        refreshControl = UIRefreshControl()
//        refreshControl?.addTarget(self, action:#selector(HomeTableViewController.refreshData), forControlEvents: .ValueChanged)
        reFreshView=ReFreshView(scrollView: self.tableView)
        reFreshView.delegate = self
        self.tableView.addSubview(reFreshView)
        
    }
    //实现代理方法
    func doReFresh(reFreshView: ReFreshView) {
        refreshData()
        reFreshView.endRefresh()
    }
    //刷新数据
    @objc func refreshData(){
        //当前最新的微博ID
        weiboContent.readContent(20, since_id: weiboContent.since_id!, max_id: 0)
        tableView.reloadData() 
        //最早的微博ID
        //停止旋转
//        refreshControl?.endRefreshing()
    }
    //加载更多数据
    @objc func addData(){
        print("加载更多")
        let row=weiboContents.count-1-2
        weiboContent.readContent(21, since_id: 0, max_id: weiboContent.max_id!)
        tableView.reloadData()
        //当前的View的row
//        let index=NSIndexPath(forRow: row, inSection: 1)
//        tableView.scrollToRowAtIndexPath(index, atScrollPosition: .Top, animated: true)
        //停止旋转
        indicatorView.stopAnimating()
    }
    func netGET(){
        //failed: unacceptable content-type: text/html
        //在使用AFN最常见的问题 没有之一
        
        
        let AFN=AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/html")
        
        SVProgressHUD.show()
        AFN.GET("https://api.weibo.com/oauth2/authorize?client_id=2357289815&redirect_url=https://www.google.com.hk", parameters: nil, success: { (task, result) in
            SVProgressHUD.dismiss()
            print("result",result)
        }) { (_, error) in
            print("error",error)
            SVProgressHUD.showErrorWithStatus("网络请求失败")
        }
    }
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return weiboContents.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let weiboCurrentContent=weiboContents[indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier(cellReUseID, forIndexPath: indexPath) as! WeiboContentCell
        cell.weiboContent=weiboCurrentContent
        
        let countByDown=weiboContents.count-indexPath.row
        if countByDown == 1 && !indicatorView.isAnimating(){
            indicatorView.startAnimating()
//            addData()
            print("加载数据")
        }
        return cell
    }
    
//    override func scrollViewDidScroll(scrollView: UIScrollView) {
//        //向上滑的距离
//        let offY=max(-(scrollView.contentOffset.y+scrollView.contentInset.top),0)
//        //scrollView上头的最大高度
//        let height:CGFloat=80
//        let progress=min(offY/height, 1.0)
//        print(progress)
//    }
}
